var layuiTable;
$(function () {
    // 加载表格数据
    layuiTable=layui.table.render({
        elem: '#tableData'
        , url: '/sys/user/list/'
        ,toolbar: '#toolbarDemo'
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'userId', title: 'ID', width: 100, unresize: true, sort: true, hide:true}
            , {field: 'username', title: '账号'}
            , {field: 'nickName', title: '昵称'}
            ,{field:'state', title:'性别', width:85, templet: '#switchTpl', unresize: true}
            , {field: 'email', title: '邮箱'}
            , {field: 'phone', title: '手机号'}
            ,{fixed: 'right', title:'操作', toolbar: '#bar', width:150}
        ]]
        ,id: 'testReload',
        page: true,
        limits: [20, 50, 100, 200],
        limit: 20
    });
    //监听状态操作
    layui.form.on('switch(stateCheck)', function(obj){
        $.ajax({
            url:"/sys/user/status/",
            type:"post",
            data:{
                userId:obj.value,
                status:obj.elem.checked
            },
            success:function (obj) {
                if (obj.code==0) {
                    layer.msg(obj.msg, {
                        icon: 1,
                        shade: 0.3,
                        time: 2000
                    }, function () {
                        //疯狂模式，关闭所有层
                        layui.table.reload();
                    });
                } else {
                    layer.msg(obj.msg, {
                        icon: 2,
                        shade: 0.3,
                        time: 1000
                    });
                }
            }
        })
    });
    //头工具栏事件
    layui.table.on('toolbar(tableData)', function(obj){
        var checkStatus = layui.table.checkStatus(obj.config.id);
        switch(obj.event){
            case 'add':
                addForm();
                break;
        };
    });
    //监听行工具事件
    layui.table.on('tool(tableData)', function(obj){
        var data = obj.data;
        //删除
        if(obj.event === 'del'){
            layer.confirm('是否删除此记录？此操作不可恢复！', function(index){
                deleteTable(data);
                var type = $(this).data('type');
                active[type] ? active[type].call(this) : '';
                layer.close(index);
            });
        } else if(obj.event === 'edit'){
            editTable(data)
        }
    });

    var $ = layui.$, active = {
        reload: function(){
            var demoReload = $('#demoReload');
            //执行重载
            layui.table.reload('testReload', {
                page: {
                    curr: 1 //重新从第 1 页开始
                }
                ,where: {
                    nickName: demoReload.val()
                }
            });
        }
    };
    roleTable();
    $('.demoTable .layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
})

/*****刷新表格***********/
function reloadTable() {
    //这里以搜索为例
    layuiTable.reload('testReload', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
    });
}

/*******新增*********/
function addForm() {
    $("#userId").attr("value",'')
    $("#formDiv input").val('')
    roleTable();
    layui.layer.open({
        type: 1,
        title: '新增',
        shadeClose: true,//点击遮罩关闭
        anim: 0,
        btnAlign: 'c',
        shade: 0.3,//是否有遮罩，可以设置成false
        maxmin: false, //开启最大化最小化按钮
        area: ['50%', '80%'],
        boolean: true,
        content:$('#formDiv'),
        success: function (layero, lockIndex) {
        },
        end: function () {
            $('#formDiv').hide();
        }
    });
}

/*****删除*******/
function deleteTable(data){
    $.ajax({
        url:"/sys/user/deleteById/"+data.userId,
        type:"get",
        success:function (obj) {
            if (obj.code==0) {
                layer.msg(obj.msg, {
                    icon: 1,
                    shade: 0.3,
                    time: 2000
                }, function () {
                    reloadTable()
                    //疯狂模式，关闭所有层
                    parent.layer.closeAll();
                });
            } else {
                layer.msg(obj.msg, {
                    icon: 2,
                    shade: 0.3,
                    time: 1000
                });
            }
        }
    })

}

/*************编辑*************************/
function  editTable(data) {
    layui.layer.open({
        type: 1,
        title: '编辑',
        shadeClose: true,//点击遮罩关闭
        anim: 0,
        btnAlign: 'c',
        shade: 0.3,//是否有遮罩，可以设置成false
        maxmin: false, //开启最大化最小化按钮
        area: ['50%', '80%'],
        boolean: true,
        content:$('#formDiv'),
        success: function (layero, lockIndex) {
            $.ajax({
                url:"/sys/user/info/" +data.userId,
                type:"get",
                success:function (r) {
                    if(r.code==0){
                        layui.use(['form'], function() {
                            //表单初始赋值
                            layui.form.val('form', {
                                "userId": data.userId
                                ,"username": r.data.username
                                ,"password": r.data.password
                                ,"nickName": r.data.nickName
                                ,"email": r.data.email
                                ,"phone": r.data.phone
                            })
                            $("#roleIds").attr("ts-selected",r.data.roleIds.join(','))
                        });
                    }else {
                        layer.msg(r.msg, {
                            icon: 2,
                            shade: 0.3,
                            time: 1000
                        });
                    }
                }
            })

        },
        end: function () {
            $('#formDiv').hide();
        }
    });
}

/*******角色表******/
function roleTable() {
    var tableSelect = layui.tableSelect;
    tableSelect.render({
        elem: '#roleIds',
        searchKey: 'roleName',
        checkedKey: 'roleId',
        searchPlaceholder: '角色名字',
        table: {
            url: '/sys/role/list/',
            cols: [[
                { type: 'checkbox' }
                , {field: 'roleId', title: 'ID', width: 100, unresize: true, sort: true, hide:true}
                , {field: 'roleName', title: '角色名称'}
                , {field: 'note', title: '备注'}
            ]]
        },
        done: function (elem, data) {
            var NEWJSON = []
            layui.each(data.data, function (index, item) {
                NEWJSON.push(item.roleName)
            })
            elem.val(NEWJSON.join(","))
        }
    })
}